# coding=utf-8

from app import app, db
from flask import render_template, request, flash, session, redirect, url_for, g
from app.models import User, Question, Answer
from datetime import datetime


@app.route("/")
def index():
    questions = Question.query.order_by('-create_time').all()

    return render_template("index.html", questions=questions)


@app.route("/register/", methods=['POST', 'GET'])
def register():
    if request.method == 'GET':
        return render_template("register.html")
    else:
        telephone = request.form.get('telephone')
        username = request.form.get('username')
        password = request.form.get('password')
        password1 = request.form.get('password1')

        if telephone is not None and password == password1 and len(telephone) == 11:
            user = User(telephone=telephone, username=username, password=password,
                        create_time=datetime.now())
            db.session.add(user)
            db.session.commit()
            return render_template("login.html")
        else:
            flash("注册失败", 'error')
            return render_template("register.html")


@app.route("/login/", methods=['POST', 'GET'])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        username = request.form.get('username')
        password = request.form.get('password')
        user = User.query.filter_by(username=username).first()
        if user and user.check_password(password):
            session['user_id'] = user.id
            session.permanent = True
            return redirect(url_for("index"))
        else:
            flash("用户名或者密码不正确", "error")
            return render_template("login.html")


@app.route("/logout/")
def logout():
    user_id = session.get("user_id")
    print("logout user_id=%s" % user_id)
    if user_id:
        session.pop('user_id', None)
    return redirect(url_for('login'))


@app.route("/question/", methods=['GET', 'POST'])
def question():
    if request.method == 'POST':
        user_id = session.get('user_id')
        title = request.form.get('title')
        question_content = request.form.get('question_content')

        user = User.query.filter(User.id == user_id).first()
        if user:
            if user_id and title and question_content:
                ques = Question(title=title, content=question_content, create_time=datetime.now(),
                                user_id=user_id)
                db.session.add(ques)
                db.session.commit()
                return redirect(url_for('index'))
            else:
                flash("问题提交失败", "error")
                return render_template("question.html")
        else:
            flash("用户未登录，请登录后重试", "error")
            return render_template("login.html")
    else:
        return render_template("question.html")


@app.route("/detail/<question_id>/", methods=['GET'])
def detail(question_id):
    q = Question.query.filter_by(id=question_id).first()
    if q:
        for a in q.answers:
            print(a.author.username)

        return render_template("detail.html", question=q)
    else:
        return "error"


@app.route("/answer/", methods=['POST'])
def answer():
    question_id = request.form.get('question_id')
    answer_content = request.form.get('answer_content')
    q = Question.query.filter_by(id=question_id).first()
    user_id = session.get('user_id')
    if q and answer_content and user_id:
        ans = Answer(content=answer_content, user_id=user_id, question_id=q.id, create_time=datetime.now())
        db.session.add(ans)
        db.session.commit()
    else:
        flash("提交的回答有错误，请检查后重新提交")
    return redirect(url_for("detail", question_id=question_id))


# @app.before_request
def my_before_request():
    user_id = session.get("user_id")
    print("before request-- %r")
    if user_id is None:
        return redirect(url_for("login"))


@app.context_processor
def my_context_processor():
    user_id = session.get("user_id")
    if user_id:
        user = User.query.filter_by(id=int(user_id)).first()
        if user:
            g.user = user
            return {"user": g.user}
    else:
        return {}
